package im.dhc.gitdiff.util;

import java.io.*;

/**
 * @author songhaichao
 * @create 2020-06-10-15:07
 **/
public class FileUtil {


    public static void makeDirs(String path){
        try {
            File target  = new File(path);
            if(target.exists()){
                target.delete();
                target.mkdirs();
            }else{
                target.mkdirs();
            }
            target = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static BufferedWriter getWriter(String type) throws Exception {
        PropertityUtil propertityUtil = new PropertityUtil();
        String onlineDate = propertityUtil.getProperty("onlineDate");
        String dir = propertityUtil.getProperty("shellDir");
        makeDirs(dir);

        File file = new File(dir+"/"+type+"_"+onlineDate+".txt");
        if(!file.exists()){
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bfw = new BufferedWriter(fw);
        return bfw;
    }

    /**
     * 复制文件
     * @param sourceFile
     * @param targetFile
     * @throws IOException
     */
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        byte[] b = null;
        try {
            if(!targetFile.exists()){
                targetFile.createNewFile();
            }
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
            b = null;
        }
    }

}
